/*eslint-disable*/
import axios from "axios";
import * as esri from "esri-leaflet";
import normalApi from "@/api/normalApi.js";
import pubsub from "pubsub-js";
import Message from "@/components/Message/showMessage";
import enterprise_keyList from "@/json/enterprise_keyList.json";
import enterprise_colorList from "@/json/enterprise_colorList.json";
import urlList from '@/store/urlList.json';


// url列表
// let urlList
// normalApi.getUrlList().then(res => {
//     urlList = res.urlList
// })


export default {
    // 图层列表
    layerList: [],
    // 套索查询启动标识
    lassoDrawingFlag: false,



    initMap() {
        // 准备gz2000坐标系参数
        const scaleDenominators = [
            4622333.68, 2311166.84, 1155583.42, 577791.71, 288895.85, 144447.93,
            72223.96, 36111.98, 18055.99, 9028.0, 4514.0, 2257.0, 1128.5, 564.25,
        ];

        const bounds = {
            top: 318728.1875,
            left: 6225.9501953125,
            bottom: 165313.25,
            leftBottom: {
                x: 6225.9501953125,
                y: 165313.25,
            },
            right: 118680.125,
            rightTop: {
                x: 118680.125,
                y: 318728.1875,
            },
        };

        // 构建gz2000坐标系
        const mapcrs = L.CRS.NonEarthCRS({
            bounds: L.bounds(
                [bounds.left, bounds.bottom],
                [bounds.right, bounds.top]
            ),
            resolutions: [
                264.5838625010584, 132.2919312505292, 52.91677250021167,
                26.458386250105836, 13.229193125052918, 6.614596562526459,
                2.6458386250105836, 0.5291677250021167, 0.13229193125052918,
            ],
            origin: L.point(-5623200.0, 10002100),
            scaleDenominators: scaleDenominators,
        });

        // 在gz2000坐标系上创建地图
        let map = L.map("leafletContainer", {
            center: [193310.628, 64273.496],
            crs: mapcrs,
            preferCanvas: true,
            maxZoom: 7,
            minZoom: 2,
            zoom: 6,
            zoomControl: false, // 隐藏缩放控件
            attributionControl: false, // 隐藏信息控件
            logoControl: false, // 隐藏logo图标
            closePopupOnClick: false,
        });

        // 暴露地图对象为公共变量
        window._map = map;

        // 添加比例尺
        L.control
            .scale({
                position: "bottomright", // 比例尺控件位置
                maxWidth: 200, // 控件宽度
                metric: true, // 显示米制单位
                imperial: false, // 隐藏英制单位
            })
            .addTo(_map);
    },

    // 添加地图图层
    addMap(data) {
        // 读取并加载图层
        let layer = esri
            .tiledMapLayer({
                url: data.url,
                useCors: false,
                opacity: 1,
            })
            .addTo(_map);

        // 存入图层数组
        this.layerList.push({
            label: data.label,
            isLanduse: data.isLanduse,
            layer,
        });
        // console.log(this.layerList);
    },

    // 清除旧标识
    deleteMarker(markerNameList) {
        // 是否删除全部标识
        let isDeleteAll = markerNameList.length === 0;
        // 数组转存
        let arr = isDeleteAll ? [1] : markerNameList;
        // 遍历
        arr.forEach((name) => {
            for (const key in _markerList) {
                let filterFlag = isDeleteAll || key === name;
                // 图层名筛选
                if (filterFlag) {
                    if (Array.isArray(_markerList[key])) {
                        // 图层数组
                        _markerList[key].forEach((layer) => {
                            _map.removeLayer(layer);
                        });
                        _markerList[key] = [];
                    } else {
                        // 单个图层
                        _markerList[key] != undefined && _map.removeLayer(_markerList[key]);
                        _markerList[key] = undefined;
                    }
                }
            }
        });
    },

    // leaflet坐标转置
    coordinateReverse(geoCoordList) {
        let resultList = [];
        geoCoordList.forEach((pointList) => {
            let list = [];
            if (pointList[0][0] > 100000) {
                list.push(pointList);
            } else {
                pointList.forEach((element) => {
                    list.push(element.reverse());
                });
            }
            resultList.push(list);
        });
        // if (list[list.length - 1] != list[0]) list.push(list[0]);
        return resultList;
    },

    // 获取屏幕点击事件的坐标
    getMapClickLocation(flag, callback) {
        let customControl = L.DomUtil.get("leafletContainer");
        if (flag) {
            customControl.onclick = function (e) {
                // 获取点击事件相对于控件的坐标
                var rect = customControl.getBoundingClientRect();
                // 存储距离
                callback(rect)
            };
        } else {
            customControl.onclick = null;
        }
    },

    // 地图点击查询
    mapClickQuery(e, callback) {
        // 信息列表重载
        pubsub.publish("infoDrawClear");
        // 视图缩放
        _map.setView(e.latlng, 7);
        // 清除旧标识
        this.deleteMarker(["highlightMark", "highlightCircle"]);
        // 绘制标识
        _markerList.highlightMark = L.marker(e.latlng).addTo(_map);
        // 读取点击坐标
        callback(e.latlng)
    },

    // 单个查询结果展示
    pointQueryResultShow(info, type) {
        let result = info;
        let text = result.attributes.qymc || result.attributes.Name
        // 要素类型读取
        type = type.split("esriGeometry")[1];
        if (type === "Polygon") {
            // 绘制面
            let centerPoint = [
                result.attributes.centerY,
                result.attributes.centerX,
            ];
            // 绘制popup
            _markerList.pointQueryResultPopup.push(
                L.popup()
                    .setLatLng(centerPoint)
                    .setContent(
                        `<div style='color:#3f69e4'>` + text + `</div>`
                    )
                    .addTo(_map)
            )
            // 转置
            let lineList = this.coordinateReverse(info.geometry.rings);
            // console.log(lineList);
            // 绘制面
            let layerList = [];
            layerList.push(
                L.polygon(lineList, {
                    color: "red",
                    fillColor: "red",
                    fillOpacity: 0.3,
                }).addTo(_map)
            );
            _markerList.pointQueryResultDraw = layerList;
            // 视图移动
            _map.fitBounds(layerList[0].getBounds());
        } else if (type === "Polyline") {
            // 绘制线
            let centerPoint = [
                result.attributes.centerY,
                result.attributes.centerX,
            ];
            // 绘制popup
            _markerList.pointQueryResultPopup.push(
                L.popup()
                    .setLatLng(centerPoint)
                    .setContent(
                        `<div style='color:#3f69e4'>` + result.attributes.NAME + `</div>`
                    )
                    .addTo(_map)
            )
            // 转置
            let lineList = this.coordinateReverse(info.geometry.paths);
            // 绘制面
            let layerList = [];
            lineList.forEach((line) => {
                layerList.push(L.polyline(line, { color: "red" }).addTo(_map));
            });
            _markerList.pointQueryResultDraw = layerList;
            // 视图移动
            _map.fitBounds(layerList[0].getBounds());
        } else {
            // 绘制点
            let centerPoint = [result.geometry.y, result.geometry.x];
            // 绘制popup
            _markerList.pointQueryResultPopup.push(
                L.popup()
                    .setLatLng(centerPoint)
                    .setContent(
                        `<div style='color:#3f69e4'>` + text + `</div>`
                    )
                    .addTo(_map)
            )
            // 视图移动
            _map.setView(centerPoint, 7);
        }
    },

    // 地图四边形框选查询-绘制点
    mapRectangularClick(e, moveFun) {
        // 清除旧标识
        this.deleteMarker(["tempRectangularPolygon", "pointQueryResultPopup", "pointQueryResultDraw"]);
        // 地图点击点坐标
        const latlng = e.latlng;
        let pointListLength = _markerList.rectangularPointList.length;
        console.log("查询面点数：" + pointListLength);
        // 首次点击
        if (pointListLength === 0) {
            _markerList.rectangularPointList[0] = [latlng.lat, latlng.lng];
            _markerList.tempRectangularPointList[0] = [latlng.lat, latlng.lng];
        }
        // 末次点击
        else if (pointListLength === 1) {
            Message("完成绘制");
            _markerList.rectangularPointList[1] = [latlng.lat, latlng.lng];
            // 绘制最终查询面
            _markerList.rectangularPolygon = L.rectangle(
                _markerList.rectangularPointList,
                { color: "#3f69e4", weight: 3 }
            ).addTo(_map);
            // 关闭鼠标移动捕捉
            _map.off("mousemove", moveFun);
            // 执行控件查询
            let queryPointList = _markerList.rectangularPolygon;
            // 查询结果信息列表隐藏
            pubsub.publish("queryInfoShow", { flag: false });
            // 传输查询面的坐标点
            pubsub.publish("polygonQueryRun", queryPointList._latlngs[0]);
        }
        // 重新绘制
        else if (pointListLength === 2) {
            Message("再次点击开始重新绘制");
            // 清除角点
            _markerList.rectangularPointList = [];
            _markerList.tempRectangularPointList = [];
            // 清除旧图层
            this.deleteMarker(["rectangularPolygon"]);
            // 重新绑定mousemove事件
            _map.on("mousemove", moveFun);
        }
    },

    // 地图四边形框选查询-绘制面
    mapRectangularMove(e) {
        // 需要不止一个点时才执行
        if (_markerList.tempRectangularPointList.length > 0) {
            // 更新长方形的边界坐标
            const latlng = e.latlng;
            _markerList.tempRectangularPointList[1] = [latlng.lat, latlng.lng];
            // 移除旧的长方形并绘制新的长方形
            this.deleteMarker(["tempRectangularPolygon"]);
            _markerList.tempRectangularPolygon = L.rectangle(
                _markerList.tempRectangularPointList,
                {
                    color: "#3f69e4",
                    weight: 3,
                }
            ).addTo(_map);
        }
    },

    // 地图多边形查询-点击绘制点
    mapPolygonClick(e) {
        Message(`双击地图以结束绘制、执行查询`);
        // 清除旧标识
        this.deleteMarker(["tempPolygonLayer", "pointQueryResultPopup", "pointQueryResultDraw"]);
        // 地图点击点坐标
        const latlng = e.latlng;
        // 前期无查询
        if (_markerList.polygonPointList.length === 0) {
            // 点位存储
            _markerList.tempPolygonPointList.push(latlng);
            // 绘制临时面
            _markerList.tempPolygonLayer = L.polygon(
                _markerList.tempPolygonPointList,
                { color: "#3f69e4", weight: 3 }
            ).addTo(_map);
        }
        // 执行新查询
        else {
            // 删除上一次查询的数据
            this.deleteMarker([
                "polygonPointList",
                "polygonLayer",
                "tempPolygonPointList",
                "tempPolygonLayer",
            ]);
            // 点位存储
            _markerList.tempPolygonPointList.push(latlng);
            // 绘制临时面
            _markerList.tempPolygonLayer = L.polygon(
                _markerList.tempPolygonPointList,
                { color: "#3f69e4", weight: 3 }
            ).addTo(_map);
        }
    },

    // 地图多边形查询-完成绘制
    mapPolygonClickConfrim(e) {
        // 清除旧标识
        this.deleteMarker(["tempPolygonLayer"]);
        // 地图点击点坐标
        const latlng = e.latlng;
        // 点位存储
        _markerList.polygonPointList = _markerList.tempPolygonPointList;
        _markerList.polygonPointList.push(latlng);
        // 绘制查询面
        _markerList.polygonLayer = L.polygon(_markerList.polygonPointList, {
            color: "#3f69e4",
            weight: 3,
        }).addTo(_map);

        // 查询结果信息列表隐藏
        pubsub.publish("queryInfoShow", { flag: false });
        // 执行查询
        pubsub.publish(
            "polygonQueryRun",
            _markerList.polygonLayer._latlngs[0]
        );
        // 视角缩放
        setTimeout(() => {
            _map.fitBounds(_markerList.polygonLayer.getBounds());
        }, 300);
    },

    // 地图套索查询-鼠标按下
    mapLassoMouseClick(e) {
        // 清除旧标识
        this.deleteMarker(["pointQueryResultPopup", "pointQueryResultDraw"])
        // 二次点击则结束绘制
        if (this.lassoDrawingFlag) {
            this.lassoDrawingFlag = false;
            // 查询结果信息列表隐藏
            pubsub.publish("queryInfoShow", { flag: false });
            // 执行查询
            pubsub.publish(
                "polygonQueryRun",
                _markerList.lassoPolygon.getLatLngs()[0]
            );
            return;
        }
        // 清除旧标识
        this.deleteMarker(["lassoLayer"])
        // 初次点击开始绘制
        this.lassoDrawingFlag = true;
        // 绘制空多边形
        _markerList.lassoLayer = L.polygon([]).addTo(_map);
        // 清空当前多边形
        _markerList.lassoLayer.setLatLngs([]);
        // 添加当前点击位置
        _markerList.lassoLayer.addLatLng(e.latlng);
    },

    // 地图套索查询-鼠标按住移动
    mapLassoMouseMove(e) {
        if (this.lassoDrawingFlag) {
            const latlngs = _markerList.lassoLayer.getLatLngs()[0];
            // 添加鼠标移动位置
            latlngs.push(e.latlng);
            // 更新多边形
            _markerList.lassoLayer.setLatLngs([latlngs]);
            // 多边形另存
            _markerList.lassoPolygon = _markerList.lassoLayer
        }
    },

    // 地址人口、企业记数展示
    addressCountDataShow(data, callback) {
        console.log(data);
        axios({
            method: "get",
            url: urlList.addressCountURL_136,
            params: {
                where: `Name='${data}'`,
                geometryType: "esriGeometryEnvelope",
                mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
                imageDisplay: "60055096",
                f: "json",
                outFields: "*",
            },
        })
            .then((result) => {
                let countData = result.data.features[0].attributes;
                // 结果数据
                callback([{
                    title: "企业",
                    listLength: countData.qyCount,
                    list: [],
                    type: "esriGeometryPoint",
                }, {
                    title: "人口",
                    listLength: countData.rkCount,
                    list: [],
                    type: "esriGeometryPoint",
                },])
            })
            .catch((err) => { });
    },

    // 要素长度决定缩放层级
    lengthToLayer(length) {
        let layer = 7 - Math.floor(length / 5000);
        return layer;
    },

    // 要素面积决定缩放层级
    areaToLayer(area) {
        let layer = 7 - Math.floor(area / 3000000);
        return layer;
    },

    // 查询结果数据总览
    seeAllData(data) {
        // console.log(data);
        // 绘制多边形集
        if (data.type.split("esriGeometry")[1] === "Polygon") {
            data.list.forEach(element => {
                // 转置
                let lineList = this.coordinateReverse(element.geometry.rings);
                // 绘制面
                _markerList.pointQueryResultDraw.push(
                    L.polygon(lineList, {
                        color: "red",
                        fillColor: "red",
                        fillOpacity: 0.3,
                    }).addTo(_map)
                )
                // 绘制popup
                let centerPoint = [
                    element.attributes.centerY,
                    element.attributes.centerX,
                ];
                _markerList.pointQueryResultPopup.push(
                    L.popup()
                        .setLatLng(centerPoint)
                        .setContent(
                            `<div style='color:#3f69e4'>` + element.attributes.Name + `</div>`
                        )
                        .addTo(_map)
                )
            });

        }
        // 绘制线集
        else {
            // 计算颜色集
            let colorList = this.colorCaclulate(data.list.length, "#FF0000", "#0000FF")
            let index = 0
            data.list.forEach(element => {
                // 转置
                let lineList = this.coordinateReverse(element.geometry.paths);
                // 绘制集
                _markerList.pointQueryResultDraw.push(
                    L.polyline(lineList, {
                        color: colorList[index],
                        fillColor: colorList[index],
                        fillOpacity: 0.3,
                    }).addTo(_map)
                )
                // 绘制popup
                let centerPoint = [
                    element.attributes.centerY,
                    element.attributes.centerX,
                ];
                _markerList.pointQueryResultPopup.push(
                    L.popup()
                        .setLatLng(centerPoint)
                        .setContent(
                            `<div style='color:${colorList[index]}'>` + element.attributes.NAME + `</div>`
                        )
                        .addTo(_map)
                )
                index++
            })

        }
    },

    // 关闭查询结果数据总览
    seeAllDataClose() {
        this.deleteMarker(["pointQueryResultDraw", "pointQueryResultPopup"])
    },

    // 颜色计算
    colorCaclulate(count, startColor, endColor) {
        if (count <= 0) return [];

        const startRgb = this.hexToRgb(startColor);
        const endRgb = this.hexToRgb(endColor);

        const colors = [];

        for (let i = 0; i < count; i++) {
            const t = i / (count - 1); // 计算插值比例

            // 计算渐变颜色的 RGB 值
            const r = Math.round(startRgb.r + t * (endRgb.r - startRgb.r));
            const g = Math.round(startRgb.g + t * (endRgb.g - startRgb.g));
            const b = Math.round(startRgb.b + t * (endRgb.b - startRgb.b));

            // 将 RGB 转换为 16 进制颜色值
            colors.push(this.rgbToHex(r, g, b));
        }

        return colors;
    },

    hexToRgb(hex) {
        // 去掉可能的前缀 #
        hex = hex.replace(/^#/, '');

        // 如果是 3 位的颜色代码，转换为 6 位
        if (hex.length === 4) {
            hex = hex.split('').map((char, i) => i === 0 ? char : char + char).join('');
        }

        // 解析红色、绿色和蓝色的值
        const r = parseInt(hex.substring(0, 2), 16);
        const g = parseInt(hex.substring(2, 4), 16);
        const b = parseInt(hex.substring(4, 6), 16);

        return { r, g, b };
    },

    rgbToHex(r, g, b) {
        // 确保每个颜色值在 0 到 255 之间，并转为 16 进制字符串
        return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
    },

    // 企业详细数据整理
    enterpriseDataHandle(enterpriseData) {
        let result = [];
        // 键值对匹配
        for (const enterpriseKey in enterpriseData) {
            for (const key in enterprise_keyList) {
                // 键值对匹配
                if (enterpriseKey === key) {
                    result.push({
                        key: enterprise_keyList[key],
                        value: enterpriseData[key],
                    });
                }
            }
        }

        // 标签列表
        let tagList = []
        enterpriseData["qybq"].split(';').forEach(tag => {
            for (const key in enterprise_colorList) {
                if (Object.hasOwnProperty.call(enterprise_colorList, key)) {
                    const color = enterprise_colorList[key];
                    // 键名匹配颜色
                    if (key === tag) {
                        tagList.push({
                            tag, color
                        })
                    }
                }
            }
        });

        return {
            result, title: enterpriseData["qymc"], tagList
        };
    }

}